package traffic;

import traffic.State;
import input.*;

import java.util.Timer;
import java.util.TimerTask;

public class Trafficlight implements IInput {

    private State state;
    private Timer timer;
    private TimerTask task;
    private class TimestepTask extends TimerTask {

        private Trafficlight light;

        TimestepTask(Trafficlight light) {
            this.light = light;
        }

        @Override
        public void run() {
            // request a timestep for trafficlight
            this.light.request(Inputs.TIMESTEP);
            this.light.reschedule(10*1000);
        }
    }

    public Trafficlight() {
        this.state = State.RED;
        // schedule the timesteptask to set up timestepping every 10sec
        this.timer = new Timer();
        this.task = new TimestepTask(this);
        this.timer.schedule(this.task, 10*1000);
        this.timer.scheduleAtFixedRate(new TimestepTask(this) {
            @Override
            public void run() {
                System.out.println(getStatus());
            }
        }, 0, 1*1001);
    }

    public String getStatus() {
        return String.format("current trafficlight state: %s", this.state.name());
    }

    // handle inputs via a request to the state machine
    public void request(Inputs input) {
        if ((input == Inputs.CARAPPROACHES && this.state == State.RED) ||
            (input == Inputs.BUTTONPEDESTRIAN && this.state == State.GREEN)) {
            reschedule(10*1000);
        }
        this.state = state.handle(input);
    }

    // miscellaneous reschedule method for timestep management
    public void reschedule(long delay) {
        this.task.cancel();
        this.task = new TimestepTask(this);
        timer.schedule(this.task, delay);
    }
}
